package com.googlecode.smartbinding.framework.core;

import com.googlecode.smartbinding.framework.core.exception.BindingException;

import java.lang.reflect.Field;
import java.util.ArrayList;
import java.util.List;

/**
 * Default implementation for {@link DataBindingManager}
 *
 * @author Iulian Dumitru
 */
public class DataBindingManagerImpl implements DataBindingManager {

    @Override
    public BindingResult bind(Object source, Object target) {

        if (source == null) {
            throw new IllegalArgumentException("Source is null!");
        }

        if (target == null) {
            throw new IllegalArgumentException("Target is null!");
        }

        Bindable bindable = target.getClass().getAnnotation(Bindable.class);
        if (bindable == null) {
            throw new IllegalArgumentException("Target must be annotated with @Bindable");
        }

        Class<?> sourceClazz = bindable.source();
        if (sourceClazz != source.getClass()) {
            throw new IllegalArgumentException("@Bindable: source must be of type " + source.getClass().getName());
        }

        String alias = bindable.alias();
        boolean noAlias = alias.length() == 0;

        List<BindingUnit> bindings = new ArrayList<BindingUnit>();

        Field[] fields = source.getClass().getDeclaredFields();

        for (Field field : fields) {

            Binding binding = field.getAnnotation(Binding.class);

            if (binding != null) {

                String targetPropertyName = binding.property();

                try {

                    Field sourceField = sourceClazz.getDeclaredField(targetPropertyName);
                    Object targetPropertyValue = field.get(target);


                } catch (NoSuchFieldException e) {

                    throw new BindingException("Error binding! NoSuchFieldException:", e);


                } catch (IllegalAccessException e) {

                    throw new BindingException("Error binding! IllegalAccessException:", e);

                }


            }


        }


        BindingContext bindingContext = new BindingContextImpl(bindings);

        return new BindingResultImpl(bindingContext);

    }

    @Override
    public boolean hasValidationErrors(BindingContext dataBindingContext) {


        return false;
    }


}
